package cn.sell.mbg.sys.adminrole.service.impl;

import cn.sell.comm.base.MySqlCrudServiceImpl;
import cn.sell.mbg.sys.adminrole.UmsAdminRoleRelation;
import cn.sell.mbg.sys.adminrole.mapper.UmsAdminRoleMapper;
import cn.sell.mbg.sys.adminrole.service.UmsAdminRoleRelationService;
import cn.sell.mbg.sys.role.UmsRole;
import cn.sell.mbg.sys.role.mapper.UmsRoleMapper;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Log4j2
@Service
@Transactional
public class UmsAdminRoleRelationServiceImpl extends MySqlCrudServiceImpl<UmsAdminRoleRelation, Long> implements UmsAdminRoleRelationService {

    @Autowired
    private UmsAdminRoleMapper umsAdminRoleMapper;


    @Autowired
    private UmsRoleMapper roleMapper;

    /**
     * 获取管理员角色
     *
     * @param adminId
     * @return
     */
    public List<UmsRole> getCheckedRole(Long adminId) {
        List<UmsRole> umsRoleList = new ArrayList<UmsRole>();
        UmsAdminRoleRelation adminRoleRelation = new UmsAdminRoleRelation();
        adminRoleRelation.setAdminId(adminId);
        List<UmsAdminRoleRelation> adminRoleRelationList = umsAdminRoleMapper.select(adminRoleRelation);
        for (UmsAdminRoleRelation umsAdminRoleRelation : adminRoleRelationList) {
            UmsRole umsRole = roleMapper.selectByPrimaryKey(umsAdminRoleRelation.getRoleId());
            umsRoleList.add(umsRole);
        }
        return umsRoleList;
    }

    /**
     * 新增或修改管理员角色
     *
     * @param adminId
     * @param roleIds
     * @return
     */
    public Long saveOrUpdateChecked(Long adminId, String roleIds) {
        Long count = 0l;

        UmsAdminRoleRelation adminRoleRelation = new UmsAdminRoleRelation();
        adminRoleRelation.setAdminId(adminId);
        umsAdminRoleMapper.delete(adminRoleRelation);

        String[] splits = roleIds.split(",");
        for (String s : splits) {
            if (StringUtils.isNotEmpty(s)) {
                long roleId = Long.valueOf(s).longValue();
                UmsAdminRoleRelation umsadminRoleRelation = new UmsAdminRoleRelation();
                umsadminRoleRelation.setAdminId(adminId);
                umsadminRoleRelation.setRoleId(roleId);
                count = count + umsAdminRoleMapper.insert(umsadminRoleRelation);
            }
        }
        if (count > 0) {
            return count;
        }
        return null;
    }

    /**
     * 删除管理员所有角色
     *
     * @param adminId
     * @return
     */
    public int deleteByAdminId(Long adminId) {
        UmsAdminRoleRelation adminRoleRelation = new UmsAdminRoleRelation();
        adminRoleRelation.setAdminId(adminId);
        return umsAdminRoleMapper.delete(adminRoleRelation);
    }


}
